import type { ElementSelectors } from '../../lib/abstract'
import type {
  ComponentStyleIdType,
  ECElementEvent,
  ECharts,
  EChartsOption,
  EchartsTitleOption,
} from '../../types/interfaces'
import type { LineChartProps } from './types'
import { UIComponent } from '../../lib/abstract'
import {
  ComponentStyleId,
  DEFAULT_ECHARTS_TITLE_TEXT_STYLE,
  logger,
} from '../../types/constants'
import { SYMBOLS } from '../../types/interfaces'
import { styles } from './styles'
import { DEFAULT_LINE_CHART_PROPS } from './types'

export class LineChart extends UIComponent<LineChartProps> {
  id: string = 'line-chart'
  readonly description: string = '折线图组件'
  readonly styleId: string = ComponentStyleId[this.name]
  private chartInstance: ECharts | null = null
  private resizeObserver: ResizeObserver | null = null

  get name(): ComponentStyleIdType {
    return 'LineChart'
  }

  get className(): string {
    return 'custom-line-chart'
  }

  constructor(props: LineChartProps) {
    super({
      ...DEFAULT_LINE_CHART_PROPS,
      ...props,
    })

    this.registerStyles()
  }

  ELEMENT_SELECTORS: ElementSelectors = {}

  /**
   * 初始化图表
   */
  private initChart(): void {
    if (!this.props.id) {
      logger.error(`[${this.name}] 容器 id 不能为空`)
      return
    }

    const container = document.getElementById(this.props.id)

    if (!container) {
      logger.error(`[${this.name}] 容器 id 为 ${this.props.id} 的元素不存在`)
      return
    }

    this.chartInstance = echarts.init(container)
    this.updateChart()

    // 添加响应式处理
    this.resizeObserver = new ResizeObserver(() => {
      this.chartInstance?.resize()
    })
    this.resizeObserver.observe(container)
  }

  /**
   * 更新图表配置
   */
  private updateChart(): void {
    if (!this.chartInstance)
      return

    const { title, titleOptions, categories, values, options, showArea, smooth, showSymbol, lineColor, areaColor, formatTooltipName } = this.props

    // 基础折线图配置
    const seriesConfig: any = {
      name: '数值',
      type: 'line',
      data: values,
      smooth,
      showSymbol,
      symbol: 'circle',
      symbolSize: 6,
      lineStyle: {
        color: lineColor,
        width: 2,
      },
      itemStyle: {
        color: lineColor,
      },
    }

    // 添加面积图配置
    if (showArea) {
      seriesConfig.areaStyle = {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0,
            color: areaColor || 'rgba(84, 112, 198, 0.3)',
          }, {
            offset: 1,
            color: 'rgba(84, 112, 198, 0.1)',
          }],
        },
      }
    }

    const defaultOptions: EChartsOption = {
      // 标题配置
      title: titleOptions || (title
        ? {
            text: title,
            textStyle: DEFAULT_ECHARTS_TITLE_TEXT_STYLE,
          } as EchartsTitleOption
        : undefined),

      // 提示框配置
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'line',
          label: {
            backgroundColor: '#6a7985',
          },
        },
        formatter: (params: any) => {
          const data = params[0]
          return `${formatTooltipName?.(data.name) || data.name}<br/>数量: ${data.value}`
        },
      },

      // 网格配置
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        top: title ? '20%' : '10%',
        containLabel: true,
      },

      // x轴配置
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: categories,
        axisLine: {
          lineStyle: {
            color: '#ccc',
          },
        },
        axisLabel: {
          color: '#666',
          interval: 0,
        },
      },

      // y轴配置
      yAxis: {
        type: 'value',
        axisLine: {
          lineStyle: {
            color: '#ccc',
          },
        },
        axisLabel: {
          color: '#666',
          formatter: '{value}',
        },
        splitLine: {
          lineStyle: {
            color: '#f0f0f0',
            type: 'dashed',
          },
        },
      },

      // 系列配置
      series: [{
        ...seriesConfig,
        ...this.props.seriesOptions,
      }],

      // 动画配置
      animation: true,
      animationDuration: 1000,
      animationEasing: 'cubicOut',

      ...options, // 允许外部覆盖默认配置
    }

    this.chartInstance.setOption(defaultOptions, true) // true表示不清除动画
  }

  /**
   * 渲染图表容器
   */
  render(): string {
    const { id, height = '300px', width = '100%' } = this.props

    return this.isEmptyData()
      ? ''
      : `
      <div id="${id}" 
        class="${this.className}" 
        style="height: ${height}; width: ${width};"
        data-chart-type="line">
      </div>
    `
  }

  /**
   * 绑定事件
   */
  bindEvents(): void {
    // 如果数据为空，不绑定事件
    if (this.isEmptyData()) {
      logger.notice(`[${this.name}] ${SYMBOLS.STATUS.WARNING} ${this.props.id} （${this.props.title || '折线图'}） 数据为空，跳过生成图表`)
      return
    }

    // 图表初始化延迟到 DOM 加载完成后
    setTimeout(() => {
      this.initChart()
      this.handleChartClick()
    }, 0)
  }

  /**
   * 处理图表点击事件
   */
  private handleChartClick(): void {
    this.chartInstance?.on('click', (params: ECElementEvent) => {
      if (params.componentType === 'series' && params.seriesType === 'line') {
        // logger.info(`[${this.name}] 折线图点击事件触发`, params)

        this.props.onClick?.(
          {
            chartId: this.props.id,
            dataIndex: params.dataIndex,
            name: params.name,
            value: params.value,
            seriesName: params.seriesName || '',
            rawData: params.data,
          },
          params.event,
        )
      }
    })
  }

  /**
   * 刷新图表数据
   */
  refresh(categories: string[], values: number[], options?: EChartsOption): void {
    if (!this.chartInstance) {
      this.initChart()
      return
    }

    try {
      this.chartInstance.setOption({
        xAxis: {
          data: categories,
        },
        series: [{
          data: values,
          ...options?.series,
        }],
        ...options,
      }, false) // false表示合并配置，不清除动画
    }
    catch (error: any) {
      logger.error(`[${this.name}] 折线图数据刷新失败`, error)
    }
  }

  /**
   * 调整图表大小
   */
  resize(): void {
    this.chartInstance?.resize()
  }

  /**
   * 检查是否为空数据
   */
  private isEmptyData(): boolean {
    const { values, renderEmpty } = this.props

    return !renderEmpty && (values.length === 0 || values.every((value: number) => value === 0))
  }

  getChartInstance(): ECharts | null {
    return this.chartInstance
  }

  /**
   * 获取样式
   */
  getStyles(): string {
    return styles(this.className)
  }

  /**
   * 销毁图表
   */
  destroy(): void {
    super.destroy()
  }

  /**
   * 清理引用
   */
  cleanupReferences(): void {
    // 清理事件监听器
    this.resizeObserver?.disconnect()
    this.resizeObserver = null

    // 销毁图表实例
    if (this.chartInstance) {
      this.chartInstance.dispose()
      this.chartInstance = null
    }
  }
}
